#!/usr/bin/env node
/* eslint-disable */

const path = require('path');
const fs = require('fs');

const LICENSES_DIRNAME = path.join(__dirname, 'licenses');
const LICENSES_REGEX_FILENAME =
  path.join(__dirname, '../src/util/normalize-manifest/licenses.js');

function clean(str) {
  return str
    .replace(/[^A-Za-z\s]/g, ' ')
    .replace(/[\s]+/g, ' ')
    .trim()
    .toLowerCase();
}

const rawRegexs = fs.readdirSync(LICENSES_DIRNAME).reduce((acc, name) => {
  const src = fs.readFileSync(path.join(LICENSES_DIRNAME, name), 'utf8');
  const rawRegex = clean(src).replace(/ wildcard /g, '(.*?| )') + '$';
  const key = name.replace(/_(\d)+$/g, '');
  const existing = acc[key];
  if (existing) {
    acc[key] = `(${rawRegex}|${existing})`;
  } else {
    acc[key] = rawRegex;
  }
  return acc;
}, {});

const inner = Object.keys(rawRegexs).map(name => {
  const escaped = JSON.stringify(rawRegexs[name]).slice(1, -1);
  return `  '${name}': new RegExp('${escaped}', 'g'),`;
}).join('\n');

const outer = `\
/* @flow */

/* eslint-disable max-len */

/**
 * DO NOT EDIT THIS FILE MANUALLY.
 * THIS FILE WAS GENERATED BY "${path.basename(__filename)}".
 */

export default {
${inner}
};
`;

fs.writeFileSync(LICENSES_REGEX_FILENAME, outer);
